<template>
  <div class="create-task" v-loading="loading">
    <h1>创建迁移任务</h1>
    <el-form :model="taskForm" label-width="120px">
      <el-form-item label="任务名称">
        <el-input v-model="taskForm.name" />
      </el-form-item>
      
      <el-card>
        <template #header>
          <div class="card-header">
            <span>源数据库配置</span>
            <el-button type="primary" size="small" @click="testSourceConnection" :loading="testingSource">
              {{ testingSource ? '测试中...' : '测试连接' }}
            </el-button>
            <el-button type="success" size="small" @click="loadSourceDatabases" :loading="loadingSourceDatabases" :disabled="!isSourceConnected">
              获取库列表
            </el-button>
          </div>
        </template>
        
        <el-form-item label="数据库类型">
          <el-select v-model="taskForm.source.type" placeholder="选择数据库类型">
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="MongoDB" value="mongodb" />
            <el-option label="Redis" value="redis" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="主机地址">
          <el-input v-model="taskForm.source.host" placeholder="主机地址" />
        </el-form-item>
        
        <el-form-item label="端口">
          <el-input v-model="taskForm.source.port" placeholder="端口" />
        </el-form-item>
        
        <el-form-item label="用户名">
          <el-input v-model="taskForm.source.user" placeholder="用户名" />
        </el-form-item>
        
        <el-form-item label="密码">
          <el-input v-model="taskForm.source.password" placeholder="密码" type="password" />
        </el-form-item>
        
        <!-- 修改为支持多数据库选择 -->
        <el-form-item label="数据库名">
          <el-select 
            v-model="taskForm.source.databases" 
            placeholder="选择数据库" 
            filterable
            allow-create
            default-first-option
            multiple
            :loading="loadingSourceDatabases"
          >
            <el-option
              v-for="db in sourceDatabases"
              :key="db"
              :label="db"
              :value="db"
            />
          </el-select>
          <div class="multi-db-tip">提示：可选择多个数据库进行批量迁移</div>
          <div v-if="taskForm.source.databases.length > 1 && taskForm.target.databases.length > 1 && taskForm.source.databases.length === taskForm.target.databases.length" class="order-warning">
            <el-alert
              title="注意：源数据库和目标数据库数量相同，系统将按照列表顺序进行一对一迁移。请确保顺序正确：第一个源数据库将迁移到第一个目标数据库，以此类推。"
              type="warning"
              show-icon
              closable
            />
          </div>
        </el-form-item>
        
        <el-alert
          v-if="sourceConnectionResult"
          :title="sourceConnectionResult.message"
          :type="sourceConnectionResult.type"
          show-icon
          closable
        />
      </el-card>
      
      <el-card>
        <template #header>
          <div class="card-header">
            <span>目标数据库配置</span>
            <el-button type="primary" size="small" @click="testTargetConnection" :loading="testingTarget">
              {{ testingTarget ? '测试中...' : '测试连接' }}
            </el-button>
            <el-button type="success" size="small" @click="loadTargetDatabases" :loading="loadingTargetDatabases" :disabled="!isTargetConnected">
              获取库列表
            </el-button>
          </div>
        </template>
        
        <el-form-item label="数据库类型">
          <el-select v-model="taskForm.target.type" placeholder="选择数据库类型">
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="MongoDB" value="mongodb" />
            <el-option label="Redis" value="redis" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="主机地址">
          <el-input v-model="taskForm.target.host" placeholder="主机地址" />
        </el-form-item>
        
        <el-form-item label="端口">
          <el-input v-model="taskForm.target.port" placeholder="端口" />
        </el-form-item>
        
        <el-form-item label="用户名">
          <el-input v-model="taskForm.target.user" placeholder="用户名" />
        </el-form-item>
        
        <el-form-item label="密码">
          <el-input v-model="taskForm.target.password" placeholder="密码" type="password" />
        </el-form-item>
        
        <!-- 修改为支持多数据库选择 -->
        <el-form-item label="数据库名">
          <el-select 
            v-model="taskForm.target.databases" 
            placeholder="选择数据库" 
            filterable
            allow-create
            default-first-option
            multiple
            :loading="loadingTargetDatabases"
          >
            <el-option
              v-for="db in targetDatabases"
              :key="db"
              :label="db"
              :value="db"
            />
          </el-select>
          <div class="multi-db-tip">提示：可选择多个数据库进行批量迁移</div>
          <div v-if="taskForm.source.databases.length > 1 && taskForm.target.databases.length > 1 && taskForm.source.databases.length === taskForm.target.databases.length" class="order-warning">
            <el-alert
              title="注意：源数据库和目标数据库数量相同，系统将按照列表顺序进行一对一迁移。请确保顺序正确：第一个源数据库将迁移到第一个目标数据库，以此类推。"
              type="warning"
              show-icon
              closable
            />
          </div>
        </el-form-item>
        
        <el-alert
          v-if="targetConnectionResult"
          :title="targetConnectionResult.message"
          :type="targetConnectionResult.type"
          show-icon
          closable
        />
      </el-card>

      <!-- 添加拖拽区域 -->
      <el-card v-if="sourceDatabases.length > 0 || targetDatabases.length > 0">
        <template #header>
          <span>数据库拖拽映射</span>
        </template>
        <div class="drag-container">
          <div class="drag-section">
            <h4>源数据库</h4>
            <div 
              class="drag-area" 
              @dragover.prevent
              @drop="onSourceDrop"
            >
              <div 
                v-for="db in sourceDatabases" 
                :key="db"
                class="drag-item"
                :class="{ selected: taskForm.source.databases.includes(db) }"
                draggable="true"
                @dragstart="onSourceDragStart($event, db)"
              >
                {{ db }}
              </div>
              <div v-if="sourceDatabases.length === 0" class="drag-placeholder">
                请先获取源数据库列表
              </div>
            </div>
          </div>
          
          <div class="drag-section">
            <h4>目标数据库</h4>
            <div 
              class="drag-area" 
              @dragover.prevent
              @drop="onTargetDrop"
            >
              <div 
                v-for="db in targetDatabases" 
                :key="db"
                class="drag-item"
                :class="{ selected: taskForm.target.databases.includes(db) }"
                draggable="true"
                @dragstart="onTargetDragStart($event, db)"
              >
                {{ db }}
              </div>
              <div v-if="targetDatabases.length === 0" class="drag-placeholder">
                请先获取目标数据库列表
              </div>
            </div>
          </div>
        </div>
      </el-card>
      
      <el-card>
        <template #header>
          <span>迁移选项</span>
        </template>
        <el-checkbox v-model="taskForm.options.migrate_schema">迁移结构</el-checkbox>
        <el-checkbox v-model="taskForm.options.migrate_data">迁移数据</el-checkbox>
        <el-checkbox v-model="taskForm.options.enable_incremental">启用增量同步</el-checkbox>
        
        <el-form-item label="过滤条件">
          <el-input 
            v-model="taskForm.options.filter_condition" 
            placeholder="SQL过滤条件，如: created_at > '2024-01-01'" 
          />
        </el-form-item>
      </el-card>

      <!-- 预检查按钮 -->
      <el-card v-if="taskForm.source.databases.length > 0 && taskForm.target.databases.length > 0">
        <template #header>
          <span>预检查</span>
        </template>
        <el-button 
          type="warning" 
          @click="runPrecheck" 
          :loading="prechecking"
          :disabled="precheckRunning"
        >
          {{ precheckRunning ? '预检查中...' : '运行预检查' }}
        </el-button>
        
        <div v-if="precheckResult" class="precheck-result">
          <el-alert 
            :type="precheckResult.success ? 'success' : 'error'" 
            :title="precheckResult.message"
            show-icon
          />
          
          <div v-if="precheckResult.details" class="precheck-details">
            <el-table :data="precheckResult.details" style="width: 100%; margin-top: 15px;">
              <el-table-column prop="sourceDb" label="源数据库" width="180" />
              <el-table-column prop="targetDb" label="目标数据库" width="180" />
              <el-table-column prop="table" label="表名" width="180" />
              <el-table-column prop="checkType" label="检查类型" width="120" />
              <el-table-column prop="status" label="状态">
                <template #default="scope">
                  <el-tag :type="scope.row.status === '通过' ? 'success' : 'danger'">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="message" label="详情" />
            </el-table>
          </div>
        </div>
      </el-card>
      
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :disabled="precheckRunning">创建任务</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
    
    <el-alert
      v-if="error"
      :title="error"
      type="error"
      show-icon
      closable
      @close="clearError"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useTaskStore } from '@/stores/task'

const router = useRouter()
const taskStore = useTaskStore()

const loading = ref(false)
const error = ref(null)

// 连接测试相关状态
const testingSource = ref(false)
const testingTarget = ref(false)
const sourceConnectionResult = ref(null)
const targetConnectionResult = ref(null)
const isSourceConnected = ref(false)
const isTargetConnected = ref(false)

// 数据库列表相关状态
const loadingSourceDatabases = ref(false)
const loadingTargetDatabases = ref(false)
const sourceDatabases = ref([])
const targetDatabases = ref([])

// 拖拽相关状态
const draggedSourceDb = ref(null)
const draggedTargetDb = ref(null)

// 预检查相关状态
const prechecking = ref(false)
const precheckRunning = ref(false)
const precheckResult = ref(null)

const taskForm = ref({
  name: '',
  source: {
    type: 'mysql',
    host: '',
    port: 3306,
    user: '',
    password: '',
    databases: [] // 修改为数组以支持多数据库
  },
  target: {
    type: 'mysql',
    host: '',
    port: 3306,
    user: '',
    password: '',
    databases: [] // 修改为数组以支持多数据库
  },
  options: {
    migrate_schema: true,
    migrate_data: true,
    enable_incremental: true,
    filter_condition: ''
  }
})

// 测试源数据库连接
const testSourceConnection = async () => {
  testingSource.value = true
  sourceConnectionResult.value = null
  try {
    // 创建一个临时的配置对象，使用第一个数据库进行连接测试
    const testConfig = {
      ...taskForm.value.source,
      database: taskForm.value.source.databases.length > 0 ? taskForm.value.source.databases[0] : ''
    }
    
    const result = await taskStore.testConnection(testConfig)
    sourceConnectionResult.value = {
      type: result.success ? 'success' : 'error',
      message: result.message
    }
    isSourceConnected.value = result.success
  } catch (err) {
    sourceConnectionResult.value = {
      type: 'error',
      message: '连接测试失败: ' + (err.message || '未知错误')
    }
    isSourceConnected.value = false
  } finally {
    testingSource.value = false
  }
}

// 测试目标数据库连接
const testTargetConnection = async () => {
  testingTarget.value = true
  targetConnectionResult.value = null
  try {
    // 创建一个临时的配置对象，使用第一个数据库进行连接测试
    const testConfig = {
      ...taskForm.value.target,
      database: taskForm.value.target.databases.length > 0 ? taskForm.value.target.databases[0] : ''
    }
    
    const result = await taskStore.testConnection(testConfig)
    targetConnectionResult.value = {
      type: result.success ? 'success' : 'error',
      message: result.message
    }
    isTargetConnected.value = result.success
  } catch (err) {
    targetConnectionResult.value = {
      type: 'error',
      message: '连接测试失败: ' + (err.message || '未知错误')
    }
    isTargetConnected.value = false
  } finally {
    testingTarget.value = false
  }
}

// 加载源数据库列表
const loadSourceDatabases = async () => {
  if (!isSourceConnected.value) return
  
  loadingSourceDatabases.value = true
  sourceDatabases.value = []
  try {
    // 创建一个临时的配置对象，不包含数据库名
    const testConfig = {
      ...taskForm.value.source,
      database: '' // 清空数据库名以获取所有数据库列表
    }
    
    const databases = await taskStore.getDatabases(testConfig)
    sourceDatabases.value = databases
  } catch (err) {
    error.value = '获取数据库列表失败: ' + (err.message || '未知错误')
  } finally {
    loadingSourceDatabases.value = false
  }
}

// 加载目标数据库列表
const loadTargetDatabases = async () => {
  if (!isTargetConnected.value) return
  
  loadingTargetDatabases.value = true
  targetDatabases.value = []
  try {
    // 创建一个临时的配置对象，不包含数据库名
    const testConfig = {
      ...taskForm.value.target,
      database: '' // 清空数据库名以获取所有数据库列表
    }
    
    const databases = await taskStore.getDatabases(testConfig)
    targetDatabases.value = databases
  } catch (err) {
    error.value = '获取数据库列表失败: ' + (err.message || '未知错误')
  } finally {
    loadingTargetDatabases.value = false
  }
}

// 拖拽相关方法
const onSourceDragStart = (event, db) => {
  draggedSourceDb.value = db
  event.dataTransfer.effectAllowed = 'copy'
}

const onTargetDragStart = (event, db) => {
  draggedTargetDb.value = db
  event.dataTransfer.effectAllowed = 'copy'
}

const onSourceDrop = (event) => {
  event.preventDefault()
  if (draggedTargetDb.value && !taskForm.value.source.databases.includes(draggedTargetDb.value)) {
    taskForm.value.source.databases.push(draggedTargetDb.value)
  }
  draggedTargetDb.value = null
}

const onTargetDrop = (event) => {
  event.preventDefault()
  if (draggedSourceDb.value && !taskForm.value.target.databases.includes(draggedSourceDb.value)) {
    taskForm.value.target.databases.push(draggedSourceDb.value)
  }
  draggedSourceDb.value = null
}

// 运行预检查
const runPrecheck = async () => {
  prechecking.value = true
  precheckRunning.value = true
  precheckResult.value = null
  
  try {
    // 模拟预检查过程
    // 实际项目中应该调用后端API进行真正的预检查
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟检查结果
    const success = Math.random() > 0.3 // 70%概率成功
    
    if (success) {
      precheckResult.value = {
        success: true,
        message: '预检查通过，可以开始迁移',
        details: generatePrecheckDetails(true)
      }
    } else {
      precheckResult.value = {
        success: false,
        message: '预检查失败，请检查数据库配置',
        details: generatePrecheckDetails(false)
      }
    }
  } catch (err) {
    precheckResult.value = {
      success: false,
      message: '预检查执行失败: ' + (err.message || '未知错误')
    }
  } finally {
    prechecking.value = false
    setTimeout(() => {
      precheckRunning.value = false
    }, 2000)
  }
}

// 生成模拟的预检查详情
const generatePrecheckDetails = (success) => {
  const details = []
  const sourceDbs = taskForm.value.source.databases
  const targetDbs = taskForm.value.target.databases
  
  // 为每个数据库对生成检查详情
  for (let i = 0; i < Math.min(sourceDbs.length, targetDbs.length); i++) {
    const sourceDb = sourceDbs[i]
    const targetDb = targetDbs[i]
    
    // 表结构检查
    details.push({
      sourceDb,
      targetDb,
      table: 'users',
      checkType: '表结构',
      status: success || Math.random() > 0.2 ? '通过' : '失败',
      message: success || Math.random() > 0.2 ? '表结构一致' : '字段类型不匹配'
    })
    
    // 主键检查
    details.push({
      sourceDb,
      targetDb,
      table: 'users',
      checkType: '主键',
      status: success || Math.random() > 0.2 ? '通过' : '失败',
      message: success || Math.random() > 0.2 ? '主键一致' : '主键定义不一致'
    })
    
    // 外键检查
    details.push({
      sourceDb,
      targetDb,
      table: 'orders',
      checkType: '外键',
      status: success || Math.random() > 0.2 ? '通过' : '失败',
      message: success || Math.random() > 0.2 ? '外键约束一致' : '外键引用不一致'
    })
    
    // 索引检查
    details.push({
      sourceDb,
      targetDb,
      table: 'products',
      checkType: '索引',
      status: success || Math.random() > 0.2 ? '通过' : '失败',
      message: success || Math.random() > 0.2 ? '索引定义一致' : '索引缺失或不一致'
    })
  }
  
  return details
}

const onSubmit = async () => {
  if (precheckRunning.value) {
    error.value = '请等待预检查完成后再提交'
    return
  }

  // 验证源数据库是否被选择
  if (taskForm.value.source.databases.length === 0) {
    error.value = '请至少选择一个源数据库'
    return
  }

  loading.value = true
  error.value = null
  try {
    // 检查是否是批量任务（任一选择了多个数据库）
    const isBatchTask = taskForm.value.source.databases.length > 1 || taskForm.value.target.databases.length > 1;

    if (isBatchTask) {
      // 批量任务处理
      // 如果源和目标数据库数量相同，但用户可能希望按照顺序迁移，添加提醒
      if (taskForm.value.source.databases.length === taskForm.value.target.databases.length) {
        // 检查是否用户可能混淆了顺序
        const needConfirmation = taskForm.value.source.databases.some((sourceDb, index) => {
          // 简单检查：如果源数据库名和目标数据库名在相同位置上相似但不相同，提醒用户
          const targetDb = taskForm.value.target.databases[index];
          return sourceDb !== targetDb && 
                 (sourceDb.includes(targetDb) || targetDb.includes(sourceDb) ||
                  Math.abs(sourceDb.length - targetDb.length) <= 2);
        });

        if (needConfirmation) {
          // 这里可以添加一个确认对话框，但为了保持简单，我们只添加注释说明
          console.log("注意：请确保源数据库和目标数据库的顺序是正确的，系统将按照列表顺序进行一对一迁移");
        }
      }

      await taskStore.createBatchTasks(taskForm.value)
    } else {
      // 单个任务处理 - 确保目标数据库名默认使用源数据库名
      let targetDatabase = '';
      if (taskForm.value.target.databases.length > 0) {
        // 如果目标数据库已指定，使用指定的
        targetDatabase = taskForm.value.target.databases[0];
      } else if (taskForm.value.source.databases.length > 0) {
        // 如果目标数据库未指定，但源数据库已指定，则使用源数据库名
        targetDatabase = taskForm.value.source.databases[0];
      } else {
        // 如果都没有指定，设置为空字符串
        targetDatabase = '';
      }

      // 构造单个任务表单
      const singleTaskForm = {
        ...taskForm.value,
        source: {
          ...taskForm.value.source,
          database: taskForm.value.source.databases.length > 0 ? taskForm.value.source.databases[0] : ''
        },
        target: {
          ...taskForm.value.target,
          database: targetDatabase  // 确保总是有目标数据库名
        }
      }
      await taskStore.createTask(singleTaskForm)
    }

    router.push('/tasks')
  } catch (err) {
    error.value = '创建任务失败: ' + (err.message || '未知错误')
  } finally {
    loading.value = false
  }
}

const clearError = () => {
  error.value = null
}

const goBack = () => {
  router.back()
}
</script>

<style scoped>
.create-task {
  padding: 20px;
}

.el-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-form-item {
  margin-bottom: 20px;
}

.multi-db-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.order-warning {
  margin-top: 10px;
}

/* 拖拽样式优化 */
.drag-container {
  display: flex;
  gap: 20px;
}

.drag-section {
  flex: 1;
}

.drag-section h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
}

.drag-area {
  min-height: 150px;
  border: 2px dashed #409eff;
  border-radius: 8px;
  padding: 15px;
  background-color: #f5f7fa;
  transition: all 0.3s;
  position: relative;
}

.drag-area:hover {
  border-color: #66b1ff;
  background-color: #eef2f7;
}

.drag-item {
  display: inline-block;
  padding: 8px 12px;
  margin: 5px;
  background-color: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  user-select: none;
}

.drag-item:hover {
  background-color: #e4e7ed;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.drag-item.selected {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.drag-placeholder {
  color: #909399;
  font-style: italic;
  text-align: center;
  padding: 20px;
}

/* 添加拖拽指示器 */
.drag-indicator {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #409eff;
  opacity: 0;
  transition: opacity 0.3s;
}

.drag-area.drag-over .drag-indicator {
  opacity: 1;
}

/* 添加连接线视觉效果 */
.drag-line {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.drag-line::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 1px;
  height: 100%;
  background-color: #409eff;
  transform: translate(-50%, -50%);
  opacity: 0.5;
}

.drag-line::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  height: 1px;
  background-color: #409eff;
  transform: translate(-50%, -50%);
  opacity: 0.5;
}

/* 优化整体布局 */
.drag-section {
  flex: 1;
  min-width: 300px;
}

.drag-container {
  gap: 20px;
  margin: 20px 0;
}

/* 预检查结果样式 */
.precheck-result {
  margin-top: 15px;
}

.precheck-details {
  margin-top: 15px;
}
</style>